package com.bangmai.service.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.spi.LoggerFactory;
import org.omg.CosNaming.IstringHelper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bangmai.beans.Order2CommodityInspection;
import com.bangmai.beans.Order2Customer;
import com.bangmai.beans.Order2Immigration;
import com.bangmai.beans.Order2Payment;
import com.bangmai.beans.Order2QiBang;
import com.bangmai.beans.Order2StockOut;
import com.bangmai.beans.OrderBody2Payment;
import com.bangmai.beans.OrderGood2CommodityInspection;
import com.bangmai.beans.OrderGood2Customer;
import com.bangmai.beans.OrderGood2Immigration;
import com.bangmai.beans.OrderGood2QiBang;
import com.bangmai.config.Config;
import com.bangmai.constant.Header;
import com.bangmai.exception.ServiceException;
import com.bangmai.model.Good;
import com.bangmai.model.GoodMapper;
import com.bangmai.model.MqGood;
import com.bangmai.model.MqMessage;
import com.bangmai.model.MqOrder;
import com.bangmai.model.Order;
import com.bangmai.model.OrderGoods;
import com.bangmai.model.OrderGoodsMapper;
import com.bangmai.model.OrderMapper;
import com.bangmai.model.OrderStatus;
import com.bangmai.model.OrderStatusMapper;
import com.bangmai.model.OrdersGoods;
import com.bangmai.model.Receiver;
import com.bangmai.model.ReceiverMapper;
import com.bangmai.service.AnalysisService;
import com.bangmai.service.CreateBeanService;
import com.bangmai.service.CustomsService;
import com.bangmai.util.ExecutorPool;
import com.bangmai.util.XmlUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class CustomsServiceImpl implements CustomsService {
	Logger logger = Logger.getLogger(CustomsServiceImpl.class.getName());
	@Autowired
	private XmlUtil xmlUtil;
	@Autowired
	private ReceiverMapper receiverMapper;
	@Autowired
	private AnalysisService analysisService;
	@Autowired
	private CreateBeanService createBeanService;
	@Autowired
	private OrderStatusMapper orderStatusMapper;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private GoodMapper goodMapper;
	@Autowired
	private OrderGoodsMapper orderGoodsMapper;
	@Autowired
	@Qualifier("pool")
	private ExecutorPool pool;
	@Autowired
	private AmqpTemplate amqpTemplate;

	@Override
	@Transactional
	public void createAndSendPacket(int type, String order_id) throws ServiceException,Exception {
		// TODO Auto-generated method stub
		if (type == 0 || type < 1 || type > 3 || String.valueOf(type) == null) {
			throw new ServiceException("参数type错误!!!");
		}
		if (order_id == null || order_id.isEmpty()) {
			throw new ServiceException("参数order_id错误!!!");
		}
		List<String> order_ids = new ArrayList<>();
		order_ids.add(order_id);
		List<Map<String, Object>> orders = orderMapper.selectOrders(order_ids);
		if (orders == null || orders.isEmpty()) {
			throw new ServiceException("没有查询到订单号为：" + order_id + "的订单!!!");
		}
		List<Map<String, Object>> mqGoods = goodMapper.selectOrderGoods(order_id);
		switch (type) {
		case 1:
			Order2Customer order2Customer = createBeanService.createCustomBean(order_id);
			boolean isSuccess_hg = xmlUtil.createCustomXml(order2Customer, order2Customer.getGoods());
			OrderStatus orderStatus_hg = new OrderStatus();
			orderStatus_hg.setOrder_id(order2Customer.getOrderId());
			orderStatus_hg.setFlag("0");
			if (isSuccess_hg) {
				logger.info("海关：上传成功");
				orderStatus_hg.setHstatus("U");
				orderStatus_hg.setHdesc("上传成功");
			} else {
				logger.info("海关：上传失败");
				orderStatus_hg.setHstatus("W");
				orderStatus_hg.setHdesc("等待上报");
			}

			orderStatusMapper.updateStatusesHg(orderStatus_hg);
			break;
		case 2:
			Order2CommodityInspection order_CommodityInspection = createBeanService
					.createCommodityInspectionBean(order_id);
			boolean isSuccess_sj = xmlUtil.createCommodityInspectionXml(order_CommodityInspection,
					order_CommodityInspection.getGoods());
			OrderStatus orderStatus_sj = new OrderStatus();
			orderStatus_sj.setOrder_id(order_CommodityInspection.getEntInsideNo());
			orderStatus_sj.setFlag("0");
			if (isSuccess_sj) {
				logger.info("上传成功");
				orderStatus_sj.setSstatus("U");
				orderStatus_sj.setSdesc("上传成功");
			} else {
				logger.info("上传失败");
				orderStatus_sj.setSstatus("W");
				orderStatus_sj.setSdesc("等待上报");
			}
			orderStatusMapper.updateStatusesSj(orderStatus_sj);

			break;
		case 3:
			Order2Payment order2Payment = createBeanService.createPaymentBean(order_id);
			Receiver receiver_payment = xmlUtil.createPaymentXml(order2Payment, order2Payment.getBodys(),
					new String[] { "MessageHead", "BizStatus", "MessageBodyList", "retInfo", "businessNo" });
			if (receiver_payment != null) {
				OrderStatus orderStatus = new OrderStatus();
				orderStatus.setOrder_id(receiver_payment.getOrder_id());
				orderStatus.setFlag("0");
				if (receiver_payment.getStatus().equals("1")) {
					orderStatus.setPstatus("U");
					orderStatus.setPresult("通联支付上报成功");
				} else {
					orderStatus.setPstatus("W");
					orderStatus.setPresult("通联支付上报失败");
				}
				orderStatus.setPdesc(receiver_payment.getInfo());
				orderStatusMapper.updateStatusesPa(orderStatus);
			}
			receiverMapper.update(receiver_payment);
			break;
		// // 南沙国际物流入库
		// case 4:
		//
		// break;
		// 南沙国际出库
		case 5:
			// List<String> order_idList =
			// orderStatusMapper.selectOrderStatus();
			// if (order_idList == null || order_idList.size() == 0) {
			// throw new ServiceException("暂无三单信息都成功申报的订单！！！");
			// }
			// List<Map<String, Object>> orderList =
			// orderMapper.selectOrders(order_ids);
			// if (orderList == null) {
			// throw new ServiceException("没有该订单信息！！！");
			// }
			// List<Order2StockOut> order2StockOuts =
			// createBeanService.createStockOutBean(orderList);
			// if (order2StockOuts != null) {
			// for (Order2StockOut order2StockOut2 : order2StockOuts) {
			// xmlUtil.createStockOutXml(order2StockOut2,
			// order2StockOut2.getGoods());
			// }
			// }
			// break;
			// 启邦物流
		case 6:
			// MqOrder mqOrder3=new MqOrder();
			// List<MqGood> mqGoods=new ArrayList<>();
			// mqOrder3.setMqGoods(mqGoods);
			// List<String> qb_order_ids =
			// orderStatusMapper.selectOrderStatus();
			// if (qb_order_ids == null || qb_order_ids.size() == 0) {
			// throw new ServiceException("暂无三单信息都成功申报的订单！！！");
			// }
			// List<Map<String, Object>> qb_orders =
			// orderMapper.selectOrders(qb_order_ids);
			// if (qb_orders == null) {
			// throw new ServiceException("没有该订单信息！！！");
			// }

			break;

		default:
			break;
		}

	}

	/**
	 * 下载，解析，存入数据库
	 */

	@Override
	@Transactional
	public void receivePacket(int type) throws Exception {
		// TODO Auto-generated method stub
		switch (type) {
		// 海关
		case 1:
			List<String> xmList = xmlUtil.downloadXml(Config.FTP_CUSTOM_HOST, Config.FTP_CUSTOM_PORT,
					Config.FTP_CUSTOM_USERNAME, Config.FTP_CUSTOM_PASSWORD, Config.FTP_CUSTOM_DOWNLOAD_LOCALFILEPATH,
					Config.FTP_CUSTOM_DOWNLOAD_FILEPATH, 1);
			if (!xmList.isEmpty()) {

				List<Receiver> receivers_custom = analysisService.analysisCustomXml(xmList,
						new String[] { "ResponseBodyList", "ResponseHead", "OldMessageId" });

				List<OrderStatus> orderStatusList = new ArrayList<>();
				for (Receiver receiver : receivers_custom) {
					OrderStatus orderStatus = new OrderStatus();
					orderStatus.setOrder_id(receiver.getOrder_id());
					String flag = orderStatusMapper.selectFlag(orderStatus);
					if (receiver.getCode() != null && receiver.getCode().equals("C01")) {

						orderStatus.setHresult("海关申报成功");
						orderStatus.setHstatus("R");
						orderStatus.setHdesc("海关申报成功");
						if (flag != null) {
							flag = String.valueOf(Integer.valueOf(flag) + 1);
						}
					} else {
						orderStatus.setHstatus("W");
						orderStatus.setHresult(receiver.getInfo());
						orderStatus.setHdesc("海关申报失败，请重新申报");
					}
					orderStatus.setHdesc(receiver.getInfo());
					orderStatus.setFlag(flag);
					orderStatusList.add(orderStatus);
					orderStatusMapper.updateStatusesHg(orderStatus);
				}
				receiverMapper.save(receivers_custom);

				// orderStatusMapper.updateStatusesHg(orderStatusList);

				// xmlUtil.deleteXmlFile(Config.FTP_CUSTOM_HOST,
				// Config.FTP_CUSTOM_PORT, Config.FTP_CUSTOM_USERNAME,
				// Config.FTP_CUSTOM_PASSWORD,
				// Config.FTP_CUSTOM_DOWNLOAD_FILEPATH);
			}
			break;
		case 2:
			// 商检
			List<String> xmList2 = xmlUtil.downloadXml(Config.FTP_CCIQ_IP, Config.FTP_CCIQ_PORT,
					Config.FTP_CCIQ_USERNAME, Config.FTP_CCIQ_PASSWORD, Config.FTP_CCIQ_DOWNLOAD_LOCALFILEPATH,
					Config.FTP_CCIQ_DOWNLOADPATH, 2);
			if (!xmList2.isEmpty()) {
				List<Receiver> receivers = analysisService.analysisCommodityinspectionXml(xmList2,
						new String[] { "Declaration", "OrgMessageID", "Status", "Notes" });
				List<OrderStatus> oList = new ArrayList<>();
				if (!receivers.isEmpty()) {
					for (Receiver receiver : receivers) {
						OrderStatus orderStatus = new OrderStatus();
						orderStatus.setOrder_id(receiver.getOrder_id());
						String flag = orderStatusMapper.selectFlag(orderStatus);
						if (receiver.getCode().equals("10")) {
							orderStatus.setSstatus("R");
							orderStatus.setSresult("商检申报成功");
							orderStatus.setSdesc("商检申报成功");
							if (flag != null) {
								flag = String.valueOf(Integer.valueOf(flag) + 1);
							}
						} else {
							orderStatus.setSstatus("W");
							orderStatus.setSresult("商检申报失败，请重新申报");
							orderStatus.setSdesc("商检申报失败，请重新申报");
						}
						orderStatus.setFlag(flag);
						orderStatus.setSdesc(receiver.getInfo());
						oList.add(orderStatus);
						orderStatusMapper.updateStatusesSj(orderStatus);
					}
					receiverMapper.save(receivers);

				}
				// xmlUtil.deleteXmlFile(Config.FTP_CCIQ_IP,
				// Config.FTP_CCIQ_PORT, Config.FTP_CCIQ_USERNAME,
				// Config.FTP_CCIQ_PASSWORD, Config.FTP_CCIQ_DOWNLOADPATH);
			}

			break;
		// 通联支付
		case 3:

			break;
		// 入库
		case 4:
			List<String> xmList3 = xmlUtil.downloadXml(Config.STOCKOUT_IP, Config.STOCKOUT_PORT,
					Config.STOCKOUT_USERNAME, Config.STOCKOUT_PASSWORD, Config.WL_STOCKOUT_LOCALFILEPATH_OUT,
					Config.STOCKOUT_DOWNLOAD_FILEPATH, 4);
			if (!xmList3.isEmpty()) {
				List<Receiver> receivers = analysisService.analysisLogisticsml(xmList3,
						new String[] { "EntInsideNo", "ReturnCode", "ReturnInfo", "MessageType" });
				if (!receivers.isEmpty()) {
					receiverMapper.save(receivers);
					for (Receiver receiver : receivers) {
						Good good = new Good();
						if (receiver.getCode().equals("1")) {
							good.setStatus("3");
						} else {
							good.setStatus("4");
						}
						goodMapper.updateGood(good);
					}
				}

				// xmlUtil.deleteXmlFile(Config.STOCKOUT_IP,
				// Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
				// Config.STOCKOUT_PASSWORD, Config.STOCKOUT_DOWNLOAD_FILEPATH);
			}
			break;
		// 出库
		case 5:
			List<String> xmList4 = xmlUtil.downloadXml(Config.STOCKOUT_IP, Config.STOCKOUT_PORT,
					Config.STOCKOUT_USERNAME, Config.STOCKOUT_PASSWORD, Config.WL_STOCKOUT_LOCALFILEPATH_OUT,
					Config.STOCKOUT_DOWNLOAD_FILEPATH, 4);
			if (!xmList4.isEmpty()) {
				List<Receiver> receivers = analysisService.analysisLogisticsml(xmList4,
						new String[] { "ResponseMessage", "ReturnCode", "ReturnInfo", "MessageType" });
				if (!receivers.isEmpty()) {
					List<OrderStatus> orderStatuses = new ArrayList<>();
					receiverMapper.save(receivers);

					for (Receiver receiver : receivers) {
						OrderStatus orderStatus = new OrderStatus();
						orderStatus.setOrder_id(receiver.getOrder_id());
						String flag = orderStatusMapper.selectFlag(orderStatus);
						if (receiver.getCode().equals("2")) {
							orderStatus.setWstatus("R");
							orderStatus.setWresult("南沙国际物流出库申报成功，等待出仓审批");
							if (flag != null) {
								flag = String.valueOf(Integer.valueOf(flag) + 1);
							}
						} else {
							orderStatus.setWstatus("W");
							orderStatus.setWresult("南沙国际物流出库申报失败，请重新申报");
							orderStatus.setWresult("南沙国际物流出库申报失败，请重新申报");
						}
						orderStatus.setWdesc(receiver.getInfo());
						orderStatus.setFlag(flag);
						orderStatusMapper.updateStatusesWl(orderStatus);
					}
					receiverMapper.save(receivers);
				}

				// xmlUtil.deleteXmlFile(Config.STOCKOUT_IP,
				// Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
				// Config.STOCKOUT_PASSWORD, Config.STOCKOUT_DOWNLOAD_FILEPATH);

			}
			break;

		default:
			break;
		}

	}

	@Override
	@Transactional
	public void insertOrder(Order order, OrderStatus orderStatus, List<OrderGoods> oGoodsList) throws Exception {
		// TODO Auto-generated method stub
		orderMapper.insertOrder(order);
		orderStatusMapper.insertStatus(orderStatus);
		orderGoodsMapper.insertOrderGoods(oGoodsList);

	}

	@Override
	@Transactional
	public void selectGoods(List<String> skuCodes) throws Exception {
		// TODO Auto-generated method stub
		goodMapper.selectGoods(skuCodes);

	}

	/**
	 * 入库操作
	 * 
	 * @param skuCode
	 * @param logistics_code
	 * @throws Exception
	 */
	@Override
	@Transactional
	public void updateGood(String skuCode, String logistics_code, String qty) throws Exception {

		Map<String, Object> map = goodMapper.selectGood(skuCode);
		if (skuCode == null || skuCode.isEmpty()) {
			throw new ServiceException("参数skuCode不能为空!!!");
		} else if (logistics_code == null || logistics_code.isEmpty()) {
			throw new ServiceException("参数logistics_code不能为空!!!");
		} else if (qty == null || qty.isEmpty()) {
			throw new ServiceException("参数qty不能为空!!!");
		} else if (Integer.valueOf(qty) <= 0) {
			throw new ServiceException("入库申报的数量必须大于零!!!");
		} else if (!logistics_code.equals("001") || !logistics_code.equals("002")) {
			throw new ServiceException("参数logistics_code只能是001(启邦物流)或者002(南沙国际物流)");
		} else if (map == null || map.isEmpty()) {
			throw new ServiceException("没有该商品的信息");
		} else {
			Good good = new Good();
			good.setSkucode(skuCode);
			good.setLogistics_code(logistics_code);
			good.setQty(qty);
			Order2Immigration order2Immigration = createBeanService.createImmigrationBean(map, qty);
			boolean isSuccess = xmlUtil.createImmigrationXml(order2Immigration, order2Immigration.getGoods());
			if (isSuccess) {
				good.setStatus("2");
				goodMapper.updateGood(good);
				goodMapper.updateGoodStatus(good);

			} else {
				throw new ServiceException("操作失败！！！");
			}
		}

	}

	/**
	 * 获取通联支付异步通知报文
	 */
	@Transactional
	@Override
	public void getPaymentNotifyXml(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		InputStream in = null;

		ByteArrayOutputStream outputStream = null;
		OutputStream oStream = null;
		in = request.getInputStream();

		outputStream = new ByteArrayOutputStream();
		byte b[] = new byte[1024];
		int size = 0;
		while ((size = in.read(b, 0, 1024)) != -1) {
			outputStream.write(b, 0, size);
		}
		byte[] bytes = outputStream.toString().getBytes("UTF-8");
		String content = new String(bytes, "UTF-8");
		oStream = response.getOutputStream();
		oStream.write("HTTPSQS_PUT_OK".getBytes());
		String xml = outputStream.toString();
		List<Receiver> receivers = analysisService.analysisPayMentNotifyXml(xml,
				new String[] { "orderNo", "status", "msg" });
		if (receivers.isEmpty()) {
			throw new ServiceException("解析报文出错！！！");
		}
		List<OrderStatus> orderStatusList = new ArrayList<>();
		for (Receiver receiver : receivers) {
			OrderStatus orderStatus = new OrderStatus();
			orderStatus.setOrder_id(receiver.getOrder_id());
			String flag = orderStatusMapper.selectFlag(orderStatus);
			if (receiver.getCode().equals("C01")) {
				orderStatus.setPstatus("R");
				orderStatus.setPresult("通联支付申报成功");
				if (flag != null) {
					flag = String.valueOf(Integer.valueOf(flag) + 1);
				}
			} else {
				orderStatus.setPstatus("w");
				orderStatus.setPresult("通联支付申报失败,请重新申报");
			}
			orderStatus.setPdesc(receiver.getInfo());
			orderStatus.setFlag(flag);
			orderStatusList.add(orderStatus);
			orderStatusMapper.updateStatus(orderStatus);
		}
		receiverMapper.save(receivers);
		try {
			outputStream.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		oStream.close();
	}

	@Transactional
	@Override
	public List<Map<String, Object>> selectOrderStatus(String order_id) throws Exception {
		// TODO Auto-generated method stub
		List<Map<String, Object>> oMaps = orderStatusMapper.selectOrder(order_id);
		return oMaps;
	}

	@Override
	public void insertOrderStatus(OrderStatus orderStatus) throws Exception {
		// TODO Auto-generated method stub

	}

	/**
	 * 出库
	 */
	@Override
	public void stockOut() throws Exception {
		List<String> order_idList = orderStatusMapper.selectOrderStatus();

		if (order_idList == null || order_idList.isEmpty()) {
			throw new ServiceException("暂无三单信息都成功申报的订单！！！");
		}
		List<Map<String, Object>> orderList = orderMapper.selectOrders(order_idList);
		if (orderList == null) {
			throw new ServiceException("没有该订单信息！！！");
		}
		for (String order_id : order_idList) {
			List<Map<String, Object>> goods = orderGoodsMapper.selelctOrderGoods(order_id);// 查出该订单下所有的商品
			logger.info("goods" + goods.size());

			if (goods == null || goods.isEmpty()) {
				logger.info("订单号为:" + order_id + "的订单下没有查询到商品信息!!!");
				break;
			}
			/**
			 * 循坏该订单下的所有商品 把同一家物流公司的商品放到一个集合中
			 */
			List<String> good_skus_qb = new ArrayList<>();
			List<String> good_skus_ns = new ArrayList<>();
			for (Map<String, Object> map : goods) {
				String good_sku = String.valueOf(map.get("sku"));

				Map<String, Object> good = goodMapper.selectGood(good_sku);
				String type = String.valueOf(good.get("logistics_code"));// 获得订单下每一个商品的物流公司编码
				logger.info(type);
				/**
				 * 将每一个商品的编码和物流公司的编码对比 并把同一个物流公司的商品的sku码放到一个集合中
				 */
				if (("001").equals(type)) {
					// 启邦物流
					good_skus_qb.add(String.valueOf(good.get("skucode")));
				} else if (("002").equals(type)) {
					// 南沙国际
					good_skus_ns.add(String.valueOf(good.get("skucode")));
					logger.info("请求南沙国际物流出库！！！");
				}
			}
			if (good_skus_ns.isEmpty()) {

			}

			nsStockOut(good_skus_ns, order_id, order_idList);// 走南沙国际物流出库
			qbStockOut(good_skus_qb, order_id, order_idList);// 走启邦物流出库

		}

	}

	/**
	 * 报关
	 * 
	 * @param types
	 * @param order_id
	 * @throws Exception
	 */

	@Override
	public void stockIn(String types, String order_id) throws Exception {
		// TODO Auto-generated method stub
		if (StringUtils.isBlank(types)) {
			throw new Exception("参数types错误!!!");
		}
		if (StringUtils.isBlank(order_id)) {
			throw new Exception("参数order_id错误!!!");
		}
		String[] arr = types.trim().split("-");
		List<String> list = Arrays.asList(arr);
		for (String string : list) {
			int type = Integer.valueOf(string);
			createAndSendPacket(type, order_id);
		}

	}

	/**
	 * 南沙物流出库
	 * 
	 * @param good_skus_ns
	 * @param order_id
	 * @param order_ids
	 * @throws Exception
	 */
	public void nsStockOut(List<String> good_skus_ns, String order_id, List<String> order_ids) throws Exception {

		if (good_skus_ns == null || good_skus_ns.isEmpty()) {
			// throw new
			// ServiceException("订单号为:"+order_id+"的订单中没有需要走南沙国际物流出库的商品");
			return;
		}
		List<Map<String, Object>> ns_order_goods_map = orderGoodsMapper.selectGoods(good_skus_ns);// 查询出order_good表中满足条件的记录
		List<Map<String, Object>> ns_order_goods = new ArrayList<>();
		// 循环遍历指定订单号下的商品
		for (Map<String, Object> map2 : ns_order_goods_map) {
			if (map2.get("order_id").equals(order_id)) {
				ns_order_goods.add(map2);
			}
		}
		List<Map<String, Object>> nsOrders = orderMapper.selectOrders(order_ids);// 查询order表获得订单记录
		List<Map<String, Object>> ns_goods_map = goodMapper.selectGoods(good_skus_ns);// 查询good表
		logger.info("order_goods_map:" + ns_order_goods_map.size());
		logger.info("order_goods:" + ns_order_goods.size());
		logger.info("qbOrders:" + nsOrders.size());
		logger.info("goods_map:" + ns_goods_map.size());
		List<Order2StockOut> order2StockOuts = createBeanService.createStockOutBean(nsOrders, ns_order_goods,
				ns_goods_map);
		if (order2StockOuts != null) {
			for (Order2StockOut order2StockOut2 : order2StockOuts) {
				boolean isSuccess = xmlUtil.createStockOutXml(order2StockOut2, order2StockOut2.getGoods());
				OrderStatus orderStatus = new OrderStatus();
				orderStatus.setOrder_id(order2StockOut2.getOrderId());
				if (isSuccess) {
					logger.info("订单号为：" + order2StockOut2.getOrderId() + "的订单南沙国际物流出库报文上传成功!!!");
					orderStatus.setWstatus("U");
					orderStatus.setWdesc("南沙国际物流出库上报成功");
				} else {
					logger.info("订单号为：" + order2StockOut2.getOrderId() + "的订单南沙国际物流出库报文上传失败!!!");
					orderStatus.setWstatus("w");
					orderStatus.setWdesc("南沙国际物流出库上报出错");
				}
				orderStatusMapper.updateStatusesWl(orderStatus);
			}
		}

	}

	/**
	 * 启邦物流出库
	 * 
	 * @param good_skus_qb
	 * @param order_id
	 * @param order_ids
	 * @throws Exception
	 */

	public void qbStockOut(List<String> good_skus_qb, String order_id, List<String> order_ids) throws Exception {
		if (good_skus_qb == null || good_skus_qb.isEmpty()) {
			// throw new ServiceException("订单号为："+order_id+"的订单中没有需要走启邦出库的商品");
			return;
		}
		List<Map<String, Object>> order_goods_map = orderGoodsMapper.selectGoods(good_skus_qb);
		List<Map<String, Object>> order_goods = new ArrayList<>();
		for (Map<String, Object> map2 : order_goods_map) {
			if (map2.get("order_id").equals(order_id)) {
				order_goods.add(map2);
			}
		}
		List<Map<String, Object>> qbOrders = orderMapper.selectOrders(order_ids);
		List<Map<String, Object>> goods_map = goodMapper.selectGoods(good_skus_qb);
		logger.info("order_goods_map:" + order_goods_map.size());
		logger.info("order_goods:" + order_goods.size());
		logger.info("qbOrders:" + qbOrders.size());
		logger.info("goods_map:" + goods_map.size());
		List<Order2QiBang> order2QiBangs = createBeanService.creatQiBangBean(qbOrders, order_goods, goods_map);
		if (order2QiBangs != null) {
			for (Order2QiBang order2QiBang : order2QiBangs) {
				Receiver receiver = xmlUtil.createQiBangXml(order2QiBang, order2QiBang.getGoods());
				OrderStatus orderStatus = new OrderStatus();
				orderStatus.setOrder_id(receiver.getOrder_id());
				System.err.println(receiver.getOrder_id());
				String flag = orderStatusMapper.selectFlag(orderStatus);
				if (receiver != null) {
					if (receiver.getStatus().equals("1")) {
						orderStatus.setWstatus("U");
						orderStatus.setWresult("启邦物流申报成功");
						if (flag != null) {
							flag = String.valueOf(Integer.valueOf(flag) + 1);
							orderStatus.setFlag(flag);
						}
					} else {
						orderStatus.setWstatus("W");
						orderStatus.setWresult("启邦物流申报失败");
						orderStatus.setFlag(flag);
					}
					orderStatus.setWdesc(receiver.getInfo());
				}
				orderStatusMapper.updateStatusesWl(orderStatus);
				receiverMapper.update(receiver);
				System.out.println(receiver.toString());
			}

		}

	}

	@Override
	public void getReceiverXml() throws Exception {
		// TODO Auto-generated method stub
		ExecutorService executor = pool.getInstance();

		executor.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				logger.info("开始扫描海关回执...");
				try {
					receivePacket(1);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		});
		// executor.execute(new Runnable() {
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// logger.info("开始扫描商检回执...");
		// try {
		// receivePacket(2);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// }
		// });
		//
		// executor.execute(new Runnable() {
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// logger.info("开始扫描入库回执...");
		// try {
		// receivePacket(4);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
		// });
		// executor.execute(new Runnable() {
		//
		// @Override
		// public void run() {
		// // TODO Auto-generated method stub
		// logger.info("开始扫描出库回执...");
		// try {
		// receivePacket(5);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		// }
		// });

	}

	@Override
	@Transactional
	public void updateOrder(Order order) throws Exception {
		// TODO Auto-generated method stub
		orderMapper.updateOrder(order);

	}

	@Override
	@Transactional
	public void sendMqmessage2Web(MqMessage mqMessage, String order_id) throws Exception {
		// TODO Auto-generated method stub
		ObjectMapper objectMapper = new ObjectMapper();
		String json = null;
		json = objectMapper.writeValueAsString(mqMessage);
		amqpTemplate.convertAndSend("custom_success", mqMessage);
		Order order = new Order();
		order.setOid(order_id);
		order.setStatus("1");
		Map<String, Object> order_map = orderMapper.selectOrder(order_id);
		if (order_map == null || order_map.isEmpty()) {
			throw new ServiceException("没有查询到订单号为：" + order_id + "的订单信息");
		}
		orderMapper.updateOrderStatus(order);
	}

}
